package com.bwie.service.Impl;

import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataSizeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.poi.StringUtils;
import com.bwie.utils.R;
import com.bwie.vo.CouponVo;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.CouponMapper;
import com.bwie.domain.Coupon;
import com.bwie.service.CouponService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

import static cn.hutool.core.date.DateUtil.now;

@Service
@Transactional(rollbackFor = Exception.class)
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements CouponService {

    @Override
    public R selectPageOfCoupon(CouponVo couponVo) {
        Page<Coupon> couponPage = new Page<>(couponVo.getPageNum(), couponVo.getPageSize());
        LambdaQueryWrapper<Coupon> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(couponVo.getCouponName()), Coupon::getCouponName, couponVo.getCouponName());
        wrapper.eq(StringUtils.isNotEmpty(couponVo.getCreateTime()), Coupon::getCreateTime, couponVo.getCreateTime());
        wrapper.eq(StringUtils.isNotEmpty(couponVo.getGoodsScope()), Coupon::getGoodsScope, couponVo.getGoodsScope());
        wrapper.eq(StringUtils.isNotEmpty(couponVo.getCreateUser()), Coupon::getCreateUser, couponVo.getCreateUser());
        wrapper.eq(StringUtils.isNotEmpty(couponVo.getEventBrand()), Coupon::getEventBrand, couponVo.getEventBrand());
        wrapper.eq(StringUtils.isNotEmpty(couponVo.getCouponType()), Coupon::getCouponType, couponVo.getCouponType());
        wrapper.eq(StringUtils.isNotEmpty(couponVo.getEventTime()), Coupon::getEventTime, couponVo.getEventTime());
        Page<Coupon> page = page(couponPage, wrapper);
        return R.OK(page);
    }

    @Override
    public R AddCoupon(Coupon coupon) {
        coupon.setCreateTime(now().toString());
        String generate = new RandomGenerator("1234567890", 3).generate();
        Date date = new Date();
        String yyyyMMddss = DateUtil.format(date, "yyyyMMddss");
        String TestId = "YHQ" + yyyyMMddss + generate;
        coupon.setCouponId(TestId);
        boolean save = save(coupon);
        return save ? R.OK() : R.ERROR(500, "新增失败");
    }
}
